import requests
import re
import json
import subprocess

def get_response(html_url):
    headers = {
        # 防盗链
        'referer': "https://www.bilibili.com/",
       'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36 Edg/90.0.818.62"
    }
    response = requests.get(url=html_url, headers=headers)
    return response

def get_video_data(html_url):
    response = get_response(html_url)
    # 获取视频url
    title = re.findall('<title data-vue-meta="true">(.*?)</title>', response.text)[0]
    title = ''.join(title.split())
    html_data = re.findall('<script>window.__playinfo__=(.*?)</script>', response.text)[0]
    json_data = json.loads(html_data)
    audio_url = json_data['data']['dash']['audio'][0]['baseUrl']
    video_url = json_data['data']['dash']['video'][0]['baseUrl']
    video_info = [title, audio_url, video_url]
    return video_info

def save(title, audio_url, video_url):
    # 保存
    audio_content = get_response(audio_url).content
    video_content = get_response(video_url).content
    with open(title + '.mp3', mode='wb') as f:
        f.write(audio_content)
    print("音频已保存")
    with open(title + '.mp4', mode='wb') as f_1:
        f_1.write(video_content)
    print("视频已保存")

# 合并音视频
def merge_data(video_name):
    print("视频合并开始：", video_name)
    name = ''.join(video_name.split())
    # ffmpeg -i video.mp4 -i audio.mp3 -c:v copy -c:a aac strict experimental output.mp4
    command = f'ffmpeg -i {name}.mp4 -i {name}.mp3 -c:v copy -c:a aac -strict experimental {name}output.mp4'
    subprocess.Popen(command, shell=True)
    print("视频合成结束：", video_name)
BV = input('请输入视频BV:')
url = 'https://www.bilibili.com/video/' + BV
video_info = get_video_data(url)
save(video_info[0], video_info[1], video_info[2])
merge_data(str(video_info[0]))
print("下载完成")
